package server

import (
	"git.inedcn.com/ined/cmn"
	"github.com/gin-gonic/gin"
	"rongyy/src/middlewares"
)

type Server struct {
	*gin.Engine
	g *gin.RouterGroup
}

func Init() *Server {
	// gin.SetMode(gin.ReleaseMode)
	s := &Server{Engine: gin.New()}

	s.Use(ErrorHandler())
	s.Use(middlewares.LoggerHandler())
	s.Static("/file", `/var/local/cd10yy-api-v2/files`)
	// s.Static("/file", `D:\Documents\Rongyy\Scszl\files`)
	s.Use(middlewares.Cors())
	s.Use(middlewares.LimitHandler(15))
	s.Use(middlewares.MerchantJwtMiddleware())

	if cmn.GetEnv("VERSION") == "master" {
		PaymentOrdersRecording()
		OrderScanner()
	}

	return s
}

func (s *Server) Listen() {
	_ = s.Run(":8099")
}

func (s *Server) Middlewares(m IMiddle) *Server {
	s.Use(func(context *gin.Context) {
		err := m.RequestError(context)
		if err != nil {
			context.AbortWithStatusJSON(400, gin.H{"error: ": err.Error()})
		} else {
			context.Next()
		}
	})
	return s
}

func (s *Server) Handle(httpMethod, relativePath string, handlers interface{}) *Server {
	if h := Convert(handlers); h != nil {
		s.g.Handle(httpMethod, relativePath, h)
	}
	return s
}

func (s *Server) GroupRouter(group string, controllers ...IController) *Server {
	s.g = s.Group(group)
	for _, c := range controllers {
		c.RouterHandler(s)
	}
	return s
}

func (s *Server) Router(controllers ...IController) *Server {
	for _, c := range controllers {
		c.RouterHandler(s)
	}
	return s
}
